package com.example.assemblyutil

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Icon
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.NumberPicker
import android.widget.TimePicker
import android.widget.TimePicker.OnTimeChangedListener
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
import com.assembly.videolist.ext.e
import com.assembly.videolist.ui.VideoDetailWindowActivity
import com.assembly.videolist.ui.VideoListActivity
import com.example.assemblyutil.tessocr.TakePhoteActivity
import com.example.assemblyutil.util.ImageSaveUtil.*
import com.example.assemblyutil.util.PermissionHelper
import com.example.assemblyutil.util.WatermarkUtils.*
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.zh.recordscreen.util.ConnectUtils
import com.zh.recordscreen.util.SoundRecordUtils
import com.zh.recordscreen.util.WifiUtils
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.title_layout.*
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream


class MainActivity : AppCompatActivity() {

    //权限请求
    private val PERMISSION_REQUEST_CODE = 1101
    private val PERMISSION_OCR_CODE = 1102
    private val REQUEST_IMAGE_CAPTURE = 1103
    private val mFilePath: String? = null
    //录屏实列对象
    private val connectServer by lazy { ConnectUtils.getInstance() }
    private val wifiServer by lazy { WifiUtils.getInstance() }
    private val permissions = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        connectServer.init(this)
        wifiServer.init(this)
        title_text.text = "AsUtils"
        initListener()


//        initData()
//        showDatePicker()
        Thread { deepFile("tessdata") }.start()

//        QuickUtils.getInstance().addShortcutCla(this
//            , MainActivity::class.java,"live_Id"
//            , "拍照识别 2"
//            , "拍照识别 2"
//            , R.mipmap.ic_takephoto_click)
//            .addShortcut(this
//                , Intent(this,MainActivity::class.java)
//                ,"vod_Id"
//                , "拍照识别 2"
//                , "拍照识别 2"
//                , R.mipmap.ic_takephoto_click)
//            .build();
        addMoreItem(this,TakePhoteActivity::class.java)
//        createDynamicShortcuts()
//        createPinShortcuts() 提交
    }

    private fun initListener() {
        video_list.setOnClickListener {
            val intent = Intent(this, VideoListActivity::class.java)
            startActivity(intent)
//            PictureSelector.create(this)
//                .openGallery(SelectMimeType.ofImage())
//                .forResult(object : OnResultCallbackListener<LocalMedia?> {
//                    override fun onResult(result: ArrayList<LocalMedia?>?) {
//
//                    }
//                    override fun onCancel() {}
//                })
        }
        down_list.setOnClickListener {
            val intent = Intent(this, DownLoadActivity::class.java)
            startActivity(intent)

//            PictureSelector.create(this)
//                .openCamera(SelectMimeType.ofImage())
//                .forResult(object : OnResultCallbackListener<LocalMedia?> {
//                    override fun onResult(result: ArrayList<LocalMedia?>?) {
//
//                    }
//                    override fun onCancel() {}
//                })
        }
        videoWindows.setOnClickListener {
            val intent = Intent(this, VideoDetailWindowActivity::class.java)
            startActivity(intent)
        }
        screenRecord.setOnClickListener {
            if (screenRecord.text == "开始录屏") {
                checkPermission(mutableListOf<String>(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO),
                    PERMISSION_REQUEST_CODE)
            } else {
                screenRecord.text = "开始录屏"
                connectServer.stopRecord()
            }
        }
        soundRecording.setOnClickListener {
            if (soundRecording.text == "开始录音") {
                soundRecording.text = "停止录音"
                SoundRecordUtils.getInstance().startRecord()
            } else {
                soundRecording.text = "开始录音"
                SoundRecordUtils.getInstance().stopRecord()
            }
        }
        photograph.setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (PermissionHelper.checkPermission(this, permissions)) {
                    val intent = Intent(this, TakePhoteActivity::class.java)
                    startActivity(intent)
                } else {
                    PermissionHelper.requestPermission(this, permissions, PERMISSION_OCR_CODE)
                }
            }
        }
        takeWatermark.setOnClickListener { //水印相机
            checkPermission(mutableListOf<String>(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA),
                REQUEST_IMAGE_CAPTURE)

        }
    }

    fun showDatePicker() {
        CardDatePickerDialog.builder(this)
            .setTitle("选择时间")
            .showBackNow(false)
            .showDateLabel(true)
            .showFocusDateInfo(false)
            .setBackGroundModel(CardDatePickerDialog.CUBE)
            .setLabelText("年", "月", "日", "时", "分")
            .setMaxTime(System.currentTimeMillis())
            .setOnChoose { millisecond ->
                Log.e("选择时间", millisecond.toString())
            }.build().show()

    }

    @SuppressLint("NewApi")
    fun initData() {
        timepicker.descendantFocusability = TimePicker.FOCUS_BLOCK_DESCENDANTS //设置点击事件不弹键盘
        timepicker.setIs24HourView(true) //设置时间显示为24小时
        timepicker.hour = 8 //设置当前小时
        timepicker.minute = 10 //设置当前分（0-59）

        timepicker.setOnTimeChangedListener(
            //获取当前选择的时间 
            OnTimeChangedListener { view, hourOfDay, minute ->

            })

        val systemResources: Resources = Resources.getSystem()
        val hourNumberPickerId: Int = systemResources.getIdentifier("hour", "id", "android")
        val minuteNumberPickerId: Int = systemResources.getIdentifier("minute", "id", "android")
        val hourNumberPicker = timepicker.findViewById(hourNumberPickerId) as NumberPicker
        val minuteNumberPicker = timepicker.findViewById(minuteNumberPickerId) as NumberPicker
        hourNumberPicker.setBackgroundColor(resources.getColor(R.color.white, null))// 修改背景颜色
        hourNumberPicker.textColor = resources.getColor(R.color.black, null)
    }

    //权限检查，连接录屏服务
    private fun checkPermission(list:MutableList<String>,code:Int) {
        val arrayN = arrayOfNulls<String>(list.size)
        list.forEachIndexed { index, s ->
            arrayN[index] = s
        }
        var isCheck = true
        list.forEach {
            if((ContextCompat.checkSelfPermission(this@MainActivity,it)!= PackageManager.PERMISSION_GRANTED)){
                isCheck = false
            }
        }
        if(isCheck){ //有权限
            when(code){
                PERMISSION_REQUEST_CODE ->{
                    connectServer.connectService()
                }
                REQUEST_IMAGE_CAPTURE ->{
                    val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                    if (takePictureIntent.resolveActivity(packageManager) != null) {
                        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
                    }
                }
            }

        }else{
            ActivityCompat.requestPermissions(
                this, arrayN, code
            )
        }
//        //调用检查权限接口进行权限检查
//        if ((ContextCompat.checkSelfPermission(
//                this@MainActivity,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE
//            )!= PackageManager.PERMISSION_GRANTED) && ContextCompat.checkSelfPermission(
//                this@MainActivity,
//                Manifest.permission.RECORD_AUDIO
//            ) != PackageManager.PERMISSION_GRANTED
//        ) {
//
//            //如果没有权限，获取权限
//            //调用请求权限接口进行权限申请
////            ActivityCompat.requestPermissions(
////                this, arrayOf<String>(
////                    Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA
////                ), PERMISSION_REQUEST_CODE
////            )
//            ActivityCompat.requestPermissions(
//                this, arrayN, code
//            )
//        } else {
//            //有权限，连接录屏服务，进行录屏
//            connectServer.connectService()
//        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_REQUEST_CODE) {
            //请求码相同
            if (grantResults.isNotEmpty() &&
                (grantResults[0] != PackageManager.PERMISSION_GRANTED ||
                        grantResults[1] != PackageManager.PERMISSION_GRANTED)
            ) {
                //如果结果都存在，但是至少一个没请求成功，弹出提示
                Toast.makeText(this, "请同意必须的应用权限，否则无法正常使用该功能！", Toast.LENGTH_SHORT).show();
            } else if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                grantResults[1] == PackageManager.PERMISSION_GRANTED
            ) {
                //如果结果都存在，两个权限都申请成功，连接服务，启动录屏
                Toast.makeText(this, "权限申请成功，用户同意！", Toast.LENGTH_SHORT).show();
                connectServer.connectService()
            }
        } else if (requestCode == PERMISSION_OCR_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                val intent = Intent(this, TakePhoteActivity::class.java)
                startActivity(intent)
            } else {
                Toast.makeText(this, "请开启权限", Toast.LENGTH_SHORT).show()
            }
        } else if (requestCode == REQUEST_IMAGE_CAPTURE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                if (takePictureIntent.resolveActivity(packageManager) != null) {
                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
                }

//                val intent = Intent()
//                intent.action = MediaStore.ACTION_IMAGE_CAPTURE // 照相机拍照
//                // 需要说明一下，以下操作使用照相机拍照，
//                // 拍照后的图片会存放在相册中的,这里使用的这种方式有一个好处就是获取的图片是拍照后的原图，
//                // 如果不实用ContentValues存放照片路径的话，拍照后获取的图片为缩略图不清晰
//                val values = ContentValues()
//                val photoUri: Uri? =
//                    contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
//                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
//                startActivityForResult(intent, REQUEST_IMAGE_CAPTURE)

//                val intent = Intent(Intent.ACTION_PICK, null)
//                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//                startActivityForResult(intent, REQUEST_IMAGE_CAPTURE)


//                val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
//                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1)
//                val out = File(getPhotopath())
//                val uri = Uri.fromFile(out)
//                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
//                startActivityForResult(intent, REQUEST_IMAGE_CAPTURE)

            } else {
                Toast.makeText(this, "请开启权限", Toast.LENGTH_SHORT).show()
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        "返回结果 $requestCode $resultCode".e()
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                1001 -> {
                    //录屏请求成功，使用工具MediaProjection录屏
                    //从发送获得的数据和结果中获取该工具

                    //录屏请求成功，使用工具MediaProjection录屏
                    connectServer.setMedia(resultCode, data)

                    screenRecord.text = "正在录屏..."
                    connectServer.startRecord()
                    "连接成功".e()
                }
                REQUEST_IMAGE_CAPTURE ->{ //水印拍照
//                    val imageBitmap: Bitmap = getBitmapFromUrl(getPhotopath(), 300.0, 400.0)
                    val extras: Bundle = data?.extras!!
                    val imageBitmap = extras["data"] as Bitmap?
                    val waterBitmap = createBitmap(imageBitmap,"水印相机","测试添加水印")
//                    val waterBitmap = addWaterMark(imageBitmap,"测试添加水印",this)

                    saveAlbum(this,waterBitmap,Bitmap.CompressFormat.JPEG,100,true)
                    "拍照回调 $imageBitmap".e()
//                    imageView.setImageBitmap(imageBitmap)
                }
            }
        }
    }

    fun deepFile(path: String) {
        var path = path
        val newPath = getExternalFilesDir(null).toString() + "/"
        try {
            val str = assets.list(path)
            if (str!!.size > 0) { //如果是目录
                val file = File(newPath + path)
                file.mkdirs()
                for (string in str) {
                    path = "$path/$string"
                    deepFile(path)
                    path = path.substring(0, path.lastIndexOf('/')) //回到原来的path
                }
            } else { //如果是文件
                val `is`: InputStream = assets.open(path)
                val fos = FileOutputStream(File(newPath + path))
                val buffer = ByteArray(1024)
                var count = 0
                while (true) {
                    count++
                    val len: Int = `is`.read(buffer)
                    if (len == -1) {
                        break
                    }
                    fos.write(buffer, 0, len)
                }
                `is`.close()
                fos.close()
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    //桌面长按添加快捷方式
    @SuppressLint("NewApi")
    fun addMoreItem(mContext: Context, cls: Class<*>) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            val arr = arrayOf("录屏", "拍照识别")
            val shortcutInfoList: MutableList<ShortcutInfo> = ArrayList()
            val shortcutManager: ShortcutManager =
                mContext.getSystemService<ShortcutManager>(ShortcutManager::class.java)
            shortcutManager.maxShortcutCountPerActivity //得到，使用ShortcutInfo.Builder设置属性
            for (i in 0..1) {
                val intent = Intent(mContext, cls::class.java)
                intent.action = Intent.ACTION_VIEW
                intent.putExtra("msg", "我和" + "聊天")
                val info = ShortcutInfo.Builder(mContext, "id$i")
                    .setShortLabel(arr[i])
                    .setLongLabel(arr[i])
                    .setIcon(Icon.createWithResource(mContext, R.mipmap.ic_takephoto_click))
                    .setIntent(intent)
                    .build()
                //当添加快捷方式的确认弹框弹出来时，将被回调
                val shortcutCallbackIntent = PendingIntent.getBroadcast(
                    mContext, 0, Intent(
                        mContext,
                        MainActivity::class.java
                    ), PendingIntent.FLAG_UPDATE_CURRENT
                )
                shortcutManager.requestPinShortcut(info, shortcutCallbackIntent.intentSender)
                shortcutInfoList.add(info)
            }
            shortcutManager.dynamicShortcuts = shortcutInfoList
        }
    }

    @SuppressLint("ObsoleteSdkInt")
    private fun createPinShortcuts() {
        // 先判断是否支持添加桌面快捷方式
        if (ShortcutManagerCompat.isRequestPinShortcutSupported(this)) {
            val pinShortcutInfo = ShortcutInfoCompat.Builder(this, "99")
                .setShortLabel(getString(R.string.recognition))
                .setLongLabel(getString(R.string.recognition))
                .setDisabledMessage(getString(R.string.recognition))
                .setIcon(IconCompat.createWithResource(this, R.mipmap.ic_takephoto_click))
                .setIntent(Intent(Intent.ACTION_VIEW).apply {
                    component = ComponentName(packageName, TakePhoteActivity::class.java.name)
                })
                .build()
            val pinnedShortcutCallbackIntent = ShortcutManagerCompat.createShortcutResultIntent(this, pinShortcutInfo)
            val successCallback = PendingIntent.getBroadcast(this, 0, pinnedShortcutCallbackIntent, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_CANCEL_CURRENT else 0)
            ShortcutManagerCompat.requestPinShortcut(this, pinShortcutInfo, successCallback.intentSender)
        }
    }

    private fun createDynamicShortcuts() {
        val dynamicShortcuts = ShortcutManagerCompat.getDynamicShortcuts(this)
        val locationShortcut = ShortcutInfoCompat.Builder(this, "100")
            .setShortLabel(getString(R.string.recognition))
            .setLongLabel(getString(R.string.recognition))
            .setDisabledMessage(getString(R.string.recognition))
            .setIcon(IconCompat.createWithResource(this, R.mipmap.ic_takephoto_click))
            .setIntent(Intent(Intent.ACTION_VIEW).apply {
                component = ComponentName(packageName, TakePhoteActivity::class.java.name)
            })
            .build()
        if (dynamicShortcuts.isEmpty() || !dynamicShortcuts.contains(locationShortcut)) {
            ShortcutManagerCompat.createShortcutResultIntent(this,locationShortcut)
//            ShortcutManagerCompat.pushDynamicShortcut(this, locationShortcut)
        }
    }

}